import { ApiResponse, Result } from '@/types/data'
import { RootThunkAction, SearchAction } from '@/types/store'
import request from '@/utils/request'
import { setLocalHistories } from '@/utils/storage'

export function getSuggestion(q: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ options: string[] }>>(
      '/suggestion',
      {
        params: {
          q,
        },
      }
    )
    dispatch({
      type: 'search/suggestion',
      payload: res.data.data.options,
    })
  }
}

export function saveHistories(histories: string[]): SearchAction {
  setLocalHistories(histories)
  return {
    type: 'search/saveHistory',
    payload: histories,
  }
}

export const getSearchResults = (
  keyword: string,
  page = 1,
  per_page = 10
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<Result>>('/search', {
      params: {
        page,
        per_page,
        q: keyword,
      },
    })
    dispatch({
      type: 'search/searchResult',
      payload: res.data.data,
    })
  }
}
